<script>
import { CommonBusinessForm } from 'jdf-common-biz';
import { getLabel, timeConvert } from 'jdf-util';
import ResearchIssueFeedbackService from '@/api/domains/researchIssueFeedback/ResearchIssueFeedbackService';
import { getWorkList } from '@/api/business/subjectManage';
import { pick } from 'lodash-es';
import listTableMixins from '@/mixins/listTableMixins';
import { showErrorMsg } from '@/api/utils/pc-message';
import FeedbackInfo from '../components/FeedbackInfo';

export default {
  extends: CommonBusinessForm,
  inject: ['jdfRenderOnCollapseHeader'],
  mixins: [listTableMixins],
  data() {
    return {
      // 后台服务
      service: new ResearchIssueFeedbackService(),
      // 需要进行主抄送重复校验的字段
      needSendDuplicateCheckFields: [],
      // 自定义校验规则
      baseRules: {},
      formData: {},
      // 表单字段布局配置
      formConfigs: [
        [
          {
            formElName: '带队领导',
            formElCode: 'leadingUserName',
          },
          {
            formElName: '调研开始日期',
            formElCode: 'researchStartDate',
          },
          {
            formElName: '调研结束日期',
            formElCode: 'researchEndDate',
          },
        ],
        [
          {
            formElName: '牵头部门',
            formElCode: 'leadingDepartmentName',
          },
          {
            formElName: '连带规范性动作类型',
            formElCode: 'normativeType',
          },
          {
            formElName: '调研对象',
            formElCode: 'researchUnitName',
          },
        ],
        [
          {
            formElName: '调研主题',
            formElCode: 'researchSubject',
          },
        ],
        [
          {
            formElName: '调研类型',
            formElCode: 'researchType',
          },
          {
            formElName: '调研区县',
            formElCode: 'grassrootsContactName',
          },
          {
            formElName: '乡镇/网络',
            formElCode: 'researchMethod',
          },

        ],
        [
          {
            formElName: '调研层级',
            formElCode: 'researchLevel',
          },
          {
            formElName: '调研形式',
            formElCode: 'researchForm',
          },
        ],
        [
          {
            formElName: '调研组联络人',
            formElCode: 'researchContactName',
          },
          {
            formElName: '被调研单位联络人',
            formElCode: 'conductResearchContactName',
          },
        ],
        [
          {
            formElName: '调研组陪同人员',
            formElCode: 'researchEntourageName',
          },
          {
            formElName: '被调研单位陪同人员',
            formElCode: 'conductResearchEntourageName',
          },
        ],
        [
          {
            formElName: '调研发现问题反馈',
            colSpan: 24,
            subTitle: true,
          },
        ],
        [
          {
            colSpan: 24,
            hideLabel: true,
            defineClassName: 'problems',
            render: (h) => h(FeedbackInfo, {
              ref: 'problems',
              props: {
                formData: this.formData,
                fieldIsEdit: (code) => (this.fieldIsEdit(code) ? '1' : '0'),
              },
              on: {
                'change-v': (val) => {
                  this.bizSet({ problems: val });
                },
              },
            }),
          },
        ],
      ],
      // 主抄送是否获取网关数据, false为不获取，true为获取
      isGateWayData: false,
      // 采用ucfg的数据字典，不采用数据库表中字典值
      isSelfDict: false,
      page: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
      },
    };
  },
  created() {
    this.renderArea();
  },
  watch: {
    'formData.title': {
      handler(val) {
        this.$emit('update:processTitle', val);
      },
    },
    /**
     * 表单数据变化时触发
     */
    formData: {
      handler(val) {
        this.$emit('changeBizFormData', val);
      },
      deep: true,
    },
  },
  methods: {
    /**
     * 表单数据初始化后调用的方法
     * */
    afterInit() {
      this.$emit('update:documentFormTitle', '调研发现问题反馈');
    },
    /**
     * 点击提交按钮后并执行表单校验后，提交窗口打开前的事件，通过throw new Error 或 return Promise.reject()阻止事件继续执行
     * 如果要执行的操作是异步的并需要等待，需return 异步方法或者await 异步方法，来实现等待
     */
    async customBeforeClickSubmitBtn() {
      await this.$refs.increaseForm.$refs.problems.customValidate();
      if (!this.formData.problems || this.formData.problems.length === 0) {
        showErrorMsg('请添加问题反馈');
        return Promise.reject();
      }
    },
    /**
     * 渲染自定义区域
     */
    renderArea() {
      if (!this.isDraftNode) {
        return
      }
      // 在折叠面板的header上渲染自定义区域的方法
      const renderOnCollapseHeaderFn = () => (
        <div class="header-right" style="flex: 1; text-align: right;">
          <el-button class="jdf-main-border-btn" onClick={this.historyWorkOrder} type="primary" size="mini">
            历史工单
          </el-button>
        </div>
      );
      // 第一个参数有渲染函数，第二个参数为要添加到的折叠面板的slot的值
      this.jdfRenderOnCollapseHeader(renderOnCollapseHeaderFn, 'base-info');
    },
    /**
     * 打开历史工单弹窗
     */
    historyWorkOrder(e) {
      e.stopPropagation();
      const { paginationAttrs } = this;
      this.customRender(
        'jdf-dialog-table',
        {
          dialogTitle: '调研工作安排',
          configs: [[{ queryLabel: '调研主题', queryField: 'researchSubject', colSpan: 8 }]],
          columns: [
            {
              type: 'selection',
              attrs: {
                'reserve-selection': true,
              },
            },
            {
              label: '调研开始日期',
              prop: 'researchStartDate',
            },
            {
              label: '调研结束日期',
              prop: 'researchEndDate',
            },
            {
              label: '带队领导',
              prop: 'leadingUserName',
            },
            {
              label: '牵头部门',
              prop: 'leadingDepartmentName',
            },
            {
              label: '调研对象',
              prop: 'researchUnitName',
            },
            {
              label: '调研主题',
              prop: 'researchSubject',
            },
            {
              label: '操作',
              render: (h, {row}) => h(
                'el-button',
                {
                  props: {
                    type: 'text',
                  },
                  on: {
                    click: () => {
                      this.$refs.increaseForm.$refs.problems.openDetail(row)
                    },
                  },
                },
                '详情',
              ),
            },
          ],
          selectKey: 'id',
          formatParam: {
            'format-list': 'list', // searchFunc中table数据对应属性为list
            'format-total': 'total', // searchFunc中数据总条数对应属性为total
            'format-number': 'page', // searchFunc中页码对应属性名为pageNum
            'format-size': 'size', // searchFunc中每页条数对应属性名为pageSize
            'search-text': '搜索', // 将“查询”按钮改为“查询”
            'reset-text': '清空', // 将“重置”按钮改为“清空”
          },
          searchMethod: this.searchFunc,
          multipleSelect: false,
          paginationAttrs,
          tableAttrs: {
            border: true,
          },
          // 输入框要展示的名称
          showNameField: 'opinion',
        },
        {
          getSelectData: (selectedData) => {
            if (selectedData && selectedData.length > 0) {
              const formFields = this.formConfigs.flat().map((item) => item.formElCode).filter((code) => code);
              formFields.push('leadingDepartmentId');
              const data = pick(selectedData[0], formFields);
              this.bizSet({ ...data, workArrangementId: selectedData[0].id });
            }
          },
        },
      );
    },
    async searchFunc(params) {
      const res = await getWorkList({
        ...params,
        approvalStatus: ['APPROVED', 'APPROVING'],
      });
      const { data: { data = {} } = {} } = res || {};
      return {
        list: data.records || [],
        total: data.total || 0,
        page: data.currentPage || 1,
        size: data.size || 10,
      };
    },
  },
};
</script>

<style scoped lang="scss">
::v-deep .btn-order .el-button {
  position: absolute;
}
::v-deep .problems > .el-form-item__content {
  padding: 0;
}
</style>
